﻿using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using Viettel.VOFFICE.DAO.Models;

namespace Viettel.VOFFICE.DAO.DAL.Repository
{
    /// <summary>
    /// menu của hệ thống
    /// </summary>
    public class SystemMenuRepository : IRepository<v_SystemMenu>
    {
        private readonly VOFFICEContext _context;

        public SystemMenuRepository(VOFFICEContext context)
        {
            if (context == null)
            {
                throw new Exception("Context must be init");
            }
            this._context = context;
        }

        #region Repository
        
        public IEnumerable<v_SystemMenu> Get()
        {
            return _context.v_SystemMenu.Select(o => o);
        }

        public v_SystemMenu GetById(object id)
        {
            return _context.v_SystemMenu.Find(id);
        }

        public IEnumerable<v_SystemMenu> FindByName(object s)
        {
            return _context.v_SystemMenu.Where(o =>ReferenceEquals(o.Name, s));
        }

        public void Insert(v_SystemMenu T)
        {
            _context.v_SystemMenu.Add(T);
            Save();
        }

        public void Delete(object id)
        {
            var systemMenu = GetById(id);
            if (systemMenu == null) return;
            Delete(systemMenu);
            Save();
        }

        public void Delete(v_SystemMenu T)
        {
            _context.v_SystemMenu.Remove(T);
            Save();
        }

        public void Update(v_SystemMenu T)
        {
            _context.Entry(T).State = EntityState.Modified;
            Save();
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        #endregion

        #region Extend Procedure

        public IEnumerable<v_SystemMenu> GetRootMenu()
        {
            return _context.v_SystemMenu.Where(s => s.ParentId.Equals(null));
        }

        public IEnumerable<v_SystemMenu> GetByParentId(int parentId)
        {
            return _context.v_SystemMenu.Where(s => s.ParentId == parentId);
        }
        #endregion

    }
}
